import React, { useEffect, useState } from 'react'

type ServerRead = {
  id: number
  name: string
  host: string
  port: number
  username: string
  description?: string | null
}

type ServerUpdate = Partial<{
  name: string
  host: string
  port: number
  username: string
  password: string
  description: string
}>

export function EditServerModal({ server, onClose, onSaved }: { server: ServerRead; onClose: () => void; onSaved: () => void }): JSX.Element {
  const [form, setForm] = useState({
    name: server.name,
    host: server.host,
    port: server.port,
    username: server.username,
    password: '',
    description: server.description || '',
  })
  const [saving, setSaving] = useState(false)

  const save = async () => {
    setSaving(true)
    try {
      const payload: ServerUpdate = {
        name: form.name,
        host: form.host,
        port: form.port,
        username: form.username,
        description: form.description,
      }
      if (form.password.trim() !== '') {
        payload.password = form.password
      }
      const resp = await fetch(`/api/servers/${server.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      })
      if (!resp.ok) throw new Error(await resp.text())
      onSaved()
      onClose()
    } catch (e) {
      console.error(e)
      alert('保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>编辑服务器</div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-sm" onClick={onClose}>取消</button>
            <button className="btn btn-primary btn-sm" onClick={save} disabled={saving}>保存</button>
          </div>
        </div>
        <div className="modal-body">
          <div className="form-grid">
            <div className="field">
              <input className="input" placeholder="名称" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </div>
            <div className="field">
              <input className="input" placeholder="主机/IP" value={form.host} onChange={(e) => setForm({ ...form, host: e.target.value })} />
            </div>
            <div className="field">
              <input className="input" placeholder="端口" type="number" value={form.port} onChange={(e) => setForm({ ...form, port: Number(e.target.value) })} />
            </div>
            <div className="field">
              <input className="input" placeholder="用户名" value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} />
            </div>
            <div className="field-3">
              <input className="input" placeholder="密码（留空则不修改）" type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
            </div>
            <div className="field-6">
              <input className="input" placeholder="描述(可选)" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

